/**
 * Copyright (C) 2013-2014 EaseMob Technologies. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *     http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.easemob.chatuidemo.activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMGroup;
import com.easemob.chat.EMGroupInfo;
import com.easemob.chat.EMGroupManager;
import com.easemob.chatuidemo.widget.ExpandGridView;
import com.easemob.exceptions.EaseMobException;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.SimpleBitmapDisplayer;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;

import net.mihome.app.AppContext;
import net.mihome.app.R;
import net.mihome.app.bean.Group;
import net.mihome.app.bean.URLs;
import net.mihome.app.bean.User;
import net.mihome.app.bean.net.ResponsePojo;
import net.mihome.app.utils.MiAsyncHttpResponseHandler;
import net.mihome.app.utils.RequestParamsFactory;
import net.mihome.app.view.MiButton;

import org.apache.http.Header;
import org.w3c.dom.Text;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class GroupSimpleDetailActivity extends BaseActivity {
	private Button btn_add_group;
	private TextView tv_admin;
	private TextView tv_name;
    private ImageView tv_avatar;
//	private TextView tv_introduction;
	private EMGroup group;
	private String groupid;
	private ProgressBar progressBar;
    private ExpandGridView userGridview;
    private GridAdapter adapter;
    private List<User> userList = new ArrayList<User>();
    private int referenceWidth;
    private int referenceHeight;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_group_simle_details);
		tv_name = (TextView) findViewById(R.id.name);
		tv_avatar = (ImageView) findViewById(R.id.avatar);
        userGridview = (ExpandGridView) findViewById(R.id.gridview);
		tv_admin = (TextView) findViewById(R.id.tv_admin);
		btn_add_group = (Button) findViewById(R.id.btn_add_to_group);
//		tv_introduction = (TextView) findViewById(R.id.tv_introduction);
		progressBar = (ProgressBar) findViewById(R.id.loading);

        String groupname="";
		final EMGroupInfo groupInfo = (EMGroupInfo) getIntent().getSerializableExtra("groupinfo");
        if(groupInfo!=null){
            groupname = groupInfo.getGroupName();
            groupid = groupInfo.getGroupId();
        }else{
            Group group1= (Group) getIntent().getSerializableExtra("groupinfo_my");
            groupname = group1.getGroupname();
            groupid = group1.getGroupid();
        }
		
		tv_name.setText(groupname);

        adapter = new GridAdapter(this, R.layout.grid, userList);
        userGridview.setAdapter(adapter);

        Drawable referenceDrawable = getResources().getDrawable(R.drawable.smiley_add_btn);
        referenceWidth = referenceDrawable.getIntrinsicWidth();
        referenceHeight = referenceDrawable.getIntrinsicHeight();
		new Thread(new Runnable() {

			public void run() {
				//从服务器获取详情
				try {
					group = EMGroupManager.getInstance().getGroupFromServer(groupid);
					runOnUiThread(new Runnable() {
						public void run() {
							progressBar.setVisibility(View.INVISIBLE);
                            ((TextView)findViewById(R.id.desc)).setText(group.getDescription());
                            ((TextView)findViewById(R.id.member_sum)).setText(group.getMembers().size()+"人");
							//获取详情成功，并且自己不在群中，才让加入圈子按钮可点击
							if(!group.getMembers().contains(EMChatManager.getInstance().getCurrentUser()))
								btn_add_group.setEnabled(true);
							tv_name.setText(group.getGroupName());
							tv_admin.setText(group.getOwner());
                            refshGroupOwnerInfo(group);
                            ImageLoader.getInstance().displayImage(URLs.MIHOME_GROUP_AVATAR+group.getGroupId()+".jpg?"+System.currentTimeMillis(),tv_avatar,options);
//                            tv_introduction.setText(group.getDescription());
						}
					});
				} catch (final EaseMobException e) {
					e.printStackTrace();
					runOnUiThread(new Runnable() {
						public void run() {
							progressBar.setVisibility(View.INVISIBLE);
							Toast.makeText(GroupSimpleDetailActivity.this, "获取圈子信息失败: "+e.getMessage(), Toast.LENGTH_LONG).show();
						}
					});
				}
				
			}
		}).start();

        getMembers(groupid);
	}
    /**
     * 从网络上获取群主信息，并将群主信息放到界面上
     * */
	public void refshGroupOwnerInfo(EMGroup group1){
        RequestParams requestParams= RequestParamsFactory.newInstance(AppContext.getInstance());
        requestParams.add("open_id",group1.getOwner());
        AppContext.ASYNC_HTTP_CLIENT.get(this,URLs.MIHOME_USER_CHAT_GET_USER_BY_OPENID,requestParams,new MiAsyncHttpResponseHandler<Map>() {
            @Override
            public void onSuccess(int arg0, Header[] arg1, ResponsePojo<Map> responsePojo) {
                User user= User.parse(responsePojo.getData());
                if(user!=null){
                    if(user.getRealName()==null||"".equals(user.getRealName())){
                        tv_admin.setText(user.getName());
                    }else{
                        tv_admin.setText(user.getRealName());
                    }
                }
            }

            @Override
            public void onFailure(int arg0, Header[] arg1, Throwable arg3) {

            }
        });
    }
	//加入圈子
	public void addToGroup(View view){
		final ProgressDialog pd = new ProgressDialog(this);
		pd.setMessage("正在发送请求...");
		pd.setCanceledOnTouchOutside(false);
		pd.show();
		new Thread(new Runnable() {
			public void run() {
				try {
					//如果是membersOnly的群，需要申请加入，不能直接join
					if(group.isMembersOnly()){
						EMGroupManager.getInstance().applyJoinToGroup(groupid, "求加入");
					}else{
						EMGroupManager.getInstance().joinGroup(groupid);
					}
					runOnUiThread(new Runnable() {
						public void run() {
							pd.dismiss();
							if(group.isMembersOnly())
								Toast.makeText(GroupSimpleDetailActivity.this, "发送请求成功，等待群主同意", Toast.LENGTH_SHORT).show();
							else
								Toast.makeText(GroupSimpleDetailActivity.this, "加入圈子成功", Toast.LENGTH_SHORT).show();
							btn_add_group.setEnabled(false);
						}
					});
				} catch (final EaseMobException e) {
					e.printStackTrace();
					runOnUiThread(new Runnable() {
						public void run() {
							pd.dismiss();
							Toast.makeText(GroupSimpleDetailActivity.this, "加入圈子失败："+e.getMessage(), Toast.LENGTH_SHORT).show();
						}
					});
				}
			}
		}).start();
	}
    /**
     * 群组成员gridadapter
     *
     * @author admin_new
     */
    private class GridAdapter extends ArrayAdapter<User> {

        private int res;
        public boolean isInDeleteMode;
        private List<User> objects;

        public GridAdapter(Context context, int textViewResourceId, List<User> objects) {
            super(context, textViewResourceId, objects);
            this.objects = objects;
            res = textViewResourceId;
            isInDeleteMode = false;
        }

        @Override
        public View getView(final int position, View convertView, final ViewGroup parent) {
            if (convertView == null) {
                convertView = LayoutInflater.from(getContext()).inflate(res, null);
            }
            MiButton button = (MiButton)  convertView.findViewById(R.id.button_avatar);
                String showUserName = getItem(position).getRealName();
                if (showUserName == null || "".equals(showUserName.trim())) {
                    showUserName = getItem(position).getUsername();
                }
                button.setText(showUserName);
                convertView.setVisibility(View.VISIBLE);
                button.setVisibility(View.VISIBLE);
                Drawable avatar = getResources().getDrawable(R.drawable.default_avatar);
                avatar.setBounds(0, 0, referenceWidth, referenceHeight);
                button.setCompoundDrawables(null, avatar, null, null);
                if (getItem(position).getFace() != null) {
                    button.setBackageFromHttp(getItem(position).getFace());
                }
            return convertView;
        }

        @Override
        public int getCount() {
            return super.getCount();
        }
    }
    /**
     * 从服务器获取到群成员信息
     */
    public void getMembers(String groupIdstr) {
        RequestParams requestParams = new RequestParams();
        requestParams.add("group_id", groupIdstr);
        AppContext.ASYNC_HTTP_CLIENT.get(this, URLs.MIHOME_USER_CHAT_GET_GROUP_MEMBERS, requestParams, new MiAsyncHttpResponseHandler<List<Map>>() {
            @Override
            public void onSuccess(int arg0, Header[] arg1, ResponsePojo<List<Map>> responsePojo) {
                List<User> list = User.parserList(responsePojo);
                userList.clear();
                userList.addAll(list);
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onFailure(int arg0, Header[] arg1, Throwable arg3) {
                arg3.printStackTrace();
                Toast.makeText(GroupSimpleDetailActivity.this, "获取好友信息失败，请见检查网络", Toast.LENGTH_SHORT).show();
            }
        });
    }
	public void back(View view){
		finish();
	}

    DisplayImageOptions options = new DisplayImageOptions.Builder()
            .showImageOnLoading(R.drawable.qunliao_common)
            .showImageForEmptyUri(R.drawable.qunliao_common) // resource or drawable
            .showImageOnFail(R.drawable.qunliao_common) // resource or drawable
            .resetViewBeforeLoading(false)  // default
            .cacheInMemory(false) // default
            .cacheOnDisk(true) // default
            .imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2) // default
            .bitmapConfig(Bitmap.Config.ARGB_8888) // default
            .displayer(new SimpleBitmapDisplayer()) // default
            .handler(new Handler()) // default
            .build();
}
